package com.etc.my.controller;


import com.etc.my.dto.CarFavoriteDto;
import com.etc.my.dto.MyMessage;
import com.etc.my.entity.User;
import com.etc.my.service.UserService;
import com.etc.my.util.IsFishing;
import com.etc.my.util.RandomValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class  UserController {

    @Autowired
    private UserService us;

    public UserService getUs() {
        return us;
    }

    public void setUs(UserService us) {
        this.us = us;
    }

    @RequestMapping("/getAllUser")
    @ResponseBody
    public MyMessage getAllUser(){
        MyMessage message = new MyMessage();
        List<User> list = us.getAllUser();

        message.setData(list);
        return message;
    }

    @RequestMapping("/userRegister")
    public void userRegister(User user, HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //获取验证码
        String randomcode_key = (String) session.getAttribute("randomcode_key");
        if(request.getParameter("catcha").equals(randomcode_key)){
            user.setUser_status("启用");
            boolean flag = us.userRegister(user);
            if(flag){
                //重新查询user
                //User loginuser = us.userLogin(user.getUser_name(), user.getUser_pwd());

                    writer.print("<script>alert('注册成功');location.href='user_login.jsp'</script>");
                    writer.flush();
                    writer.close();

            }
        }else{
            writer.print("<script>alert('验证码错误');location.href='register.jsp'</script>");
            writer.flush();
            writer.close();
        }
        //登入失败 跳转到注册界面
        writer.print("<script>alert('注册失败');location.href='register.jsp'</script>");
        writer.flush();
        writer.close();
    }

    @RequestMapping("/userlogin")
    public void userlogin(User user, HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        User userLogin = us.userLogin(user.getUser_phone(), user.getUser_pwd());
        String randomcode_key = (String) session.getAttribute("randomcode_key");
        IsFishing isFishing=new IsFishing();
        if(isFishing.isFishing(request)){
            if(request.getParameter("catcha").equals(randomcode_key)){
                if(user == null | user.getUser_phone() == null | user.getUser_pwd() == null | userLogin == null ){
                    writer.print("<script>alert('登入失败，用户名和密码错误');location.href='user_login.jsp'</script>");
                    writer.flush();
                    writer.close();
                }else if("禁用".equals(userLogin.getUser_status())){
                    writer.print("<script>alert('登入失败，该账号已被禁用！');location.href='user_login.jsp'</script>");
                    writer.flush();
                    writer.close();
                }else{
                    //存入请求域
                    session.setAttribute("loginuser",userLogin);
                    writer.print("<script>alert('登入成功');location.href='index.jsp'</script>");
                    writer.flush();
                    writer.close();
                }
            }else{
                writer.print("<script>alert('验证码错误');location.href='user_login.jsp'</script>");
                writer.flush();
                writer.close();
            }
        }else {
            writer.print("<script>alert('您的账号信息可能被盗取，请立即修改信息！！！');location.href='user_login.jsp'</script>");
            writer.flush();
            writer.close();
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginuser");
        return "index";
    }

    /**
     * 获取生成验证码显示到 UI 界面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value="/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");

        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证吗校验
     * @param session
     * @return
     */
    @RequestMapping("/catcha")
    @ResponseBody
    public String catcha(HttpSession session){
        String randomcode_key = (String) session.getAttribute("randomcode_key");
        return randomcode_key;
    }


    @RequestMapping("/updateUser")
    public void updateUser(User user,HttpSession session,HttpServletResponse response)throws Exception{
        //获取session的user
        User loginuser = (User) session.getAttribute("loginuser");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(user.getUser_pwd() == null | user.getUser_pwd() == ""){
            //密码为空的判断
            user.setUser_pwd(loginuser.getUser_pwd());
        }if(user.getUser_name() == null | user.getUser_name() == ""){
            user.setUser_name(loginuser.getUser_name());
        }
        boolean flag = us.updateUser(user);
        if(flag){
            session.removeAttribute("loginuser");
            //重新存入请求域
            session.setAttribute("loginuser",us.queryUserById(loginuser.getUser_id()));
            writer.print("<script>alert('修改成功');location.href='userhome.jsp'</script>");
            writer.flush();
            writer.close();
        }
        else{
            writer.print("<script>alert('修改失败');location.href='userhome.jsp'</script>");
            writer.flush();
            writer.close();
        }

    }
    //获取推送信息
    @RequestMapping("/getFavorite")
    @ResponseBody
    public MyMessage getFavorite(CarFavoriteDto carFavoriteDto,HttpServletRequest request){
        MyMessage myMessage = new MyMessage();
        //page，size默认值
        Integer page = carFavoriteDto.getPage();
        Integer size = carFavoriteDto.getSize();
        User user= (User) request.getSession().getAttribute("loginuser");
        //size.page.maxPage容错
        size = size <= 0 ? 5 : size;
        page = page <= 0 ? 1 : page;
        Long count = us.getFavoriteCount(user.getUser_id());
        Integer maxPage = (int) (count % size == 0 ? (count / size) : (count / size + 1));
        page = page > maxPage ? maxPage : page;
        List<CarFavoriteDto> list = us.getFavoriteCar(user.getUser_id(),(page-1)*size,size);
        carFavoriteDto.setPage(page);
        carFavoriteDto.setSize(size);
        myMessage.setData(list);
        myMessage.setPage(page);
        myMessage.setSize(size);
        myMessage.setMaxPage(maxPage);

        return myMessage;
    }

    //判断是否为唯一电话
    @RequestMapping("/queryUserByPhone")
    @ResponseBody
    public boolean queryUserByPhone(HttpServletRequest request){
        String user_phone = request.getParameter("user_phone");
        return us.queryUserByPhone(user_phone);
    }
}
